package com.kcs.fxmargin.action;

import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.ImportDepositWithdrawActionForm;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.ImportDepositWithdrawBO;
import com.kcs.fxmargin.service.ImportDepositWithdrawService;

public class ImportDepositWithdrawAction extends FXAction {
	
	private Logger log = Logger.getLogger(Constant.LOG_FX);

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ImportDepositWithdrawActionForm bean = null;
		ImportDepositWithdrawBO bo = null;
		ImportDepositWithdrawService svc = null;
		LoginActionForm userInfo = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
		log.info("Begin : ImportDepositWithdrawAction : process");
		
		try{
			request.setCharacterEncoding("ISO-8859-1");
			bean = (ImportDepositWithdrawActionForm)form;
			bean.setUserLoginId(userInfo.getUserId());
			bean.setUserLoginName(userInfo.getUserName());
			bean.setUserLoginRoleId(userInfo.getRoleId());
			
			System.out.println("userId: "+bean.getUserLoginId());
			System.out.println("userName: "+bean.getUserLoginName());
			System.out.println("userRole: "+bean.getUserLoginRoleId());
			
			bo = new ImportDepositWithdrawBO();
			svc = new ImportDepositWithdrawService();
			
			log.info("tranCode="+bean.getTranCode());
			
			if(bean.getTranCode().equals("")){
				bean.resetForm();
			}else if(bean.getTranCode().equals("searchImportDW")){
				if(validateSearchImportDWList(bean,request)){
					bo.setInCifNo(bean.getInCifNo());
					bo.setInACName(bean.getInACName());
					bo.setInStartDate(bean.getInStartDate());
					bo.setInEndDate(bean.getInEndDate());
					
					if(bean.getSearchType().equals(Constant.SEARCH_TYPE_DIFF)){
						bo = svc.getImportDWListDiff(bo);
					}else{
						bo = svc.getImportDWList(bo);
					}
					
					
					bean.setImportDWList(bo.getImportDWList());
					request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
				}
			
			}else if(bean.getTranCode().equals("printImportDW")){
				exportImportDWListToExcel(bean.getImportDWList(), bean.getInCifNo(), bean.getInACName(), bean.getInEndDate(), bean.getInEndDate(), bean.getUserLoginName(), response);
				request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
			
			}else if(bean.getTranCode().equals("resetForm")){
				bean.resetForm();
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute(Constant.ERR_ATTR, e+"");
			
		}finally{
			if(bean != null){
				bean.setTranCode("");
			}
		}

		log.info("End : ImportDepositWithdrawAction : process");
		return mapping.findForward("importDepositWithdraw");
	}
	
	private boolean validateSearchImportDWList(ImportDepositWithdrawActionForm bean, HttpServletRequest request){
		boolean result = false;
		log.info("Begin : ImportDepositWithdrawAction : validateSearchImportDWList");
		
		if (bean.getInCifNo().equals("") && bean.getInACName().equals("") && bean.getInStartDate().equals("") && bean.getInEndDate().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, Constant.ERR_SEARCH_IMPORT_DW_CONDITION);
			result = false;
		}else{
			if (!bean.getInStartDate().equals("")){
				if(!bean.getInEndDate().equals("")){
					if(commonUtils.checkDateFormat(bean.getInStartDate()) && commonUtils.checkDateFormat(bean.getInEndDate())){
						if(commonUtils.checkBetweenDate(bean.getInStartDate(), bean.getInEndDate())){
							result = true;
						}else{
							request.setAttribute(Constant.ERR_ATTR, Constant.ERR_DATE_BETWEEN);
							result = false;
						}
					}else{
						request.setAttribute(Constant.ERR_ATTR, Constant.ERR_DATE_FORMAT);
						result = false;
					}
				}else{
					request.setAttribute(Constant.ERR_ATTR, Constant.ERR_DATE_BETWEEN);
					result = false;
				}
				
			}else{
				if(!bean.getInEndDate().equals("")){
					request.setAttribute(Constant.ERR_ATTR, Constant.ERR_DATE_BETWEEN);
					result = false;
				}else{
					result = true;
				}
			}
		}
		
		log.info("result: "+result);
		log.info("End : ImportDepositWithdrawAction : validateSearchImportDWList");
		return result;
	}
	
	@SuppressWarnings("deprecation")
	public void exportImportDWListToExcel(List<ImportDepositWithdrawBO> importDWList, String cifNo, String customerName, String startDate, String endDate, String userName, HttpServletResponse response)throws Exception{
		ServletOutputStream out = null;
		HSSFWorkbook workbook = null;
		HSSFSheet sheet = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		ImportDepositWithdrawBO idw = null;
		HSSFCellStyle style = null;
		HSSFFont font = null;
		int rowCnt = 0;
		
		log.info("Begin : ImportDepositWithdrawAction : exportImportDWListToExcel");
		
		if(importDWList != null && importDWList.size()>0){
			workbook = new HSSFWorkbook();
			
			sheet = workbook.createSheet("DiffReport");
			sheet.getPrintSetup().setLandscape(true);
			sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); 
			sheet.setFitToPage(true);
			sheet.getPrintSetup().setScale((short)100);
			
			//Criteria
			font = workbook.createFont();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style = workbook.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
			style.setFont(font);
			style.setWrapText(false);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("CIF No. : "+cifNo);
			cell.setCellStyle(style);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Customer Name : "+customerName);
			cell.setCellStyle(style);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Start Date : "+startDate);
			cell.setCellStyle(style);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("End Date : "+endDate);
			cell.setCellStyle(style);
			
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 9));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 9));
			sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 9));
			
			row = sheet.createRow(rowCnt++);
			
			//-- Header cell style
			style = workbook.createCellStyle();
			font = workbook.createFont();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setFont(font);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setFillForegroundColor(new HSSFColor.AQUA().getIndex());
			
			row = sheet.createRow(rowCnt++);
			
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("No.");
			cell.setCellStyle(style);
			cell = row.createCell(1, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Date");
			cell.setCellStyle(style);
			cell = row.createCell(2, Cell.CELL_TYPE_STRING);
			cell.setCellValue("CIF No.");
			cell.setCellStyle(style);
			cell = row.createCell(3, Cell.CELL_TYPE_STRING);
			cell.setCellValue("A/C No.");
			cell.setCellStyle(style);
			cell = row.createCell(4, Cell.CELL_TYPE_STRING);
			cell.setCellValue("A/C Name");
			cell.setCellStyle(style);
			cell = row.createCell(5, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Type");
			cell.setCellStyle(style);
			cell = row.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Amount(THB)");
			cell.setCellStyle(style);
			cell = row.createCell(7, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Ref. No.");
			cell.setCellStyle(style);
			cell = row.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Entry By");
			cell.setCellStyle(style);
					
			for(int i=0; i<importDWList.size(); i++){
				idw = importDWList.get(i);
				
				row = sheet.createRow(rowCnt++);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				cell = row.createCell(0, Cell.CELL_TYPE_STRING);
				cell.setCellValue(i+1);
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				cell = row.createCell(1, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getDate());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(2, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getCifNo());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(3, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getAcNo());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(4, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getAcName());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(5, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getTypeName());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(6, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getAmount());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(7, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getRefNo());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(8, Cell.CELL_TYPE_STRING);
				cell.setCellValue(idw.getEntryBy());
				cell.setCellStyle(style);

			}
			
			for(int s=0; s<=8; s++){
				sheet.autoSizeColumn((short)s);
			}
			
			HSSFFooter footer = sheet.getFooter();
			footer.setLeft("Print by : "+userName);
			footer.setRight("Print Date : "+commonUtils.getcurrentDatetime());
			
			response.setHeader("Pragma", "no-cache");
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename="+Constant.EXCEL_DIFF_IMPORT_DW_FILENAME);
			
			out = response.getOutputStream();
			workbook.write(out);
			out.flush();
			out.close();
			
			log.info("Export excel successfully.");
			
		}else{
			throw new Exception("Cannot export Excel: Data error.");
		}
		 
		log.info("End : ImportDepositWithdrawAction : exportImportDWListToExcel");
	}

}
